package com.cositas.dulces.lp.promo2012;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cositas.dulces.lp.promo2012.dbentities.Participant;
import com.cositas.dulces.lp.promo2012.dbentities.Recommendation;
import com.cositas.dulces.lp.promo2012.utils.ActionsPoints;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;

public class RecommendAction implements Action {
	
	public void doAction(HttpServletRequest req, HttpServletResponse resp) throws EntityNotFoundException, IOException {
		String uid = req.getParameter("uid"); // el que invita
		String request_ids = req.getParameter("request_ids"); // invitaciones
		String invitations[] = request_ids.split(",");
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		long nano = System.nanoTime();
		for (String invitationSt : invitations) {
			// para cada uno va separado por _
			// 0 es invitacion, 1 es el invitado
			if (invitationSt.contains("_")) {
				String invitation[] = invitationSt.split("_");
				// todo buscar que la invitacion no haya sido hecha antes...
				Query query = new Query(Recommendation.entity_name).addFilter(Recommendation.field_fromfbid, FilterOperator.EQUAL, uid)
					.addFilter(Recommendation.field_tofbid, FilterOperator.EQUAL, invitation[1]);
				List<Entity> recommendation = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1));
				if (recommendation.isEmpty()) {
					// inserto la invitacion
					Key k = KeyFactory.createKey(Recommendation.entity_name, uid + "-" + (nano++));
					Entity reco = new Entity(k);
					reco.setProperty(Recommendation.field_fromfbid, uid);
					reco.setProperty(Recommendation.field_recid, invitation[0]);
					reco.setProperty(Recommendation.field_tofbid, invitation[1]);
					datastore.put(reco);
					// sumar puntos al que recomendo...
					Key participantKey = KeyFactory.createKey(Participant.entity_name, uid);
					Entity participant = datastore.get(participantKey);
					Integer account = Integer.valueOf((String)participant.getProperty(Participant.field_points));
					account = account + ActionsPoints.RECOMMENDATION_POINTS;
					participant.setProperty(Participant.field_points, account.toString());
					datastore.put(participant);
				}
			}
		}
		resp.getWriter().print("OK");
	}
}
